# -*- coding: utf-8 -*-
"""
Created on Wed Apr  3 10:37:26 2024

@author: 刘翼
"""

import cv2
import numpy as np

def gradient_basic(image):  #基本梯度
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    dst = cv2.morphologyEx(binary, cv2.MORPH_GRADIENT, kernel)
    cv2.imshow("gradient", dst)
def gradient_in_out(image):
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    dm = cv2.dilate(image, kernel)
    em = cv2.erode(image, kernel)
    dst1 = cv2.subtract(image, em) # 内部梯度
    dst2 = cv2.subtract(dm, image) # 外部梯度
    cv2.imshow("internal", dst1)
    cv2.imshow("external", dst2)
def gradient_X(image):
    kernel_x = np.array([[0,0,0],[1,1,1],[0,0,0]], dtype=np.uint8)
    dmx = cv2.dilate(image, kernel_x)
    emx = cv2.erode(image, kernel_x)
    dstx = cv2.subtract(dmx, emx)   # X方向梯度
    cv2.imshow("X-direction", dstx)
def gradient_Y(image):
    kernel_y = np.array([[0,1,0],[0,1,0],[0,1,0]], dtype=np.uint8)
    dmy = cv2.dilate(image, kernel_y)
    emy = cv2.erode(image, kernel_y)
    dsty = cv2.subtract(dmy, emy)   # Y方向梯度
    cv2.imshow("Y-direction", dsty)    
    
src = cv2.imread(r"C:\Users\Public\opencv\Figure\Elephant.png")
cv2.namedWindow("original", cv2.WINDOW_AUTOSIZE)
cv2.imshow("original", src)
gradient_basic(src)
gradient_in_out(src)
gradient_X(src)
gradient_Y(src)
cv2.waitKey(0)
cv2.destroyAllWindows()